/*
Copyright (c) 2011, Stephane Albert
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the organization nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL STEPHANE ALBERT BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <iostream>
#include <string>
#include <curl/curl.h>
#include <cstring>

#include "config.h"
#include "global.h"
#include "debridManager.h"

void printUsage() {
    std::cout << _("Usage: autodebrid [OPTION]") << std::endl;
    std::cout << _("autodebrid is a small utility designed to automatically debrid and fetch download links via online services.") << std::endl;
    std::cout << _("General options: ") << std::endl;
    std::cout << _("  -v, --version\tPrint informations about the version of this software.") << std::endl;
    std::cout << _("  -h, --help\tShow this help message.") << std::endl;
    std::cout << _("  -i, --interactive-config\tStart the wizard to generate a configuration file.") << std::endl;
    std::cout << _("  -w, --wizard\tSame as -i.") << std::endl;
    std::cout << _("  -c, --config-file CONFIG_FILE\tOverride the default configuration path for CONFIG_FILE.") << std::endl;
    #if INTERACTIVE_PASSWORD > 0
        std::cout << _("  -cp, --cipher-password [PASSWORD]\tGenerate a ciphered password if PASSWORD isn't defined stdin will be used, program will then exit.") << std::endl;
    #endif
}

void printMiniUsage() {
    std::cout << _("For more informations try: \"autodebrid -h\"") << std::endl;
}

void printVersion () {
    std::cout << "AutoDebrid v" << VERSION << std::endl;
}

int main(int argc, char **argv) {
    /*
     *  Locales settings
     */
    setlocale(LC_ALL, "");
    #ifndef WIN32
    bindtextdomain("autodebrid", "/usr/share/locale");
    #else
    bindtextdomain("autodebrid", "locale");
    #endif
    textdomain("autodebrid");

    debridManager fetcherManager;
    bool configLoaded = false;

    /*
     *  Command line parameters handling
     */
    for (int i = 1; i < argc; ++i) {
        if (!strcmp(argv[i], "-c") || !strcmp(argv[i], "--config-file")) {
            ++i;
            if (argc != i && strncmp(argv[i], "-", 1)) {
                configLoaded = fetcherManager.loadConfig(argv[i]);
            }
            else {
                std::cout << _("Wrong usage: -c, --config-file CONFIG_FILE\nUnrecognized parameter: ") << argv[i] << std::endl;
                printMiniUsage();
                return -1;
            }
        }
        else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--version")) {
            printVersion();
            return 0;
        }
        else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
            printUsage();
            return 0;
        }
        else if (!strcmp(argv[i], "-i") || !strcmp(argv[i], "--interactive-config")) {
            configLoaded = fetcherManager.interactiveConfiguration();
        }
        else if (!strcmp(argv[i], "-w") || !strcmp(argv[i], "--wizard")) {
            configLoaded = fetcherManager.interactiveConfiguration();
        }
        #if INTERACTIVE_PASSWORD > 0
        else if (!strcmp(argv[i], "-cp") || !strcmp(argv[i], "--cipher-password")) {
            ++i;
            if (argc == i || !strncmp(argv[i], "-", 1)) {
                std::string password;
                std::cout << _("Enter the password to cipher: ");
                std::cin >> password;
                std::cout << debridManager::cipherPass(password) << std::endl;
            }
            else
                std::cout << debridManager::cipherPass(argv[i]) << std::endl;
            return 0;
        }
        #endif
        else {
            std::cout << _("Unknown command: ") << argv[i] << std::endl;
            printMiniUsage();
            return -1;
        }
    }

    if (!configLoaded)
        configLoaded = fetcherManager.loadConfig(DEFAULT_CONFIG);
    if (!configLoaded) {
        std::cerr << _("Unable to load config.") << std::endl;
        return -1;
    }

    /*
     * Init CURL Lib
     */
    CURLcode retCode;
    #ifdef WIN32
        retCode = curl_global_init(CURL_GLOBAL_WIN32);
    #else
        retCode = curl_global_init(CURL_GLOBAL_NOTHING);
    #endif

    if (retCode != 0) {
        std::cerr << _("Error while initializing cURL.") << std::endl;
        return -1;
    }

    if (fetcherManager.start()) {
        while (std::cin.get() != 'q');
        fetcherManager.clearFetchers();
    }

    curl_global_cleanup();
    return 0;
}
